<?php
error_reporting(E_ALL^E_NOTICE);
date_default_timezone_set('Asia/Shanghai');
$savePath = 'upload/';
$fileName = md5(date('YmdHis') . rand(1000, 9999)) . '.jpg';
if (!file_exists($savePath)) {
    mkdir($savePath);
}

$data = base64_decode($_POST['picdata']);
$code = 0;
if (!$fp = @fopen($savePath . $fileName, 'wd')) {
    $code = 500;
} else {
    flock($fp, LOCK_EX);
    fwrite($fp, $data);
    flock($fp, LOCK_UN);
    fclose($fp);
}

$fullName = $savePath . $fileName;
$time = date('Y-m-d H:i:s');


//引入db类
require 'mysqli.php';
//实例化db类
$db = new Db(['host'=>'localhost','user'=>'root','pass'=>'root','name'=>'capture']);
//截图图片的路径和时间保存到数据库
$curr_id = $db->insertOne('capture','img_path,create_time',"'$fullName','$time'");

////上一张图片的id
//$prev_id = $curr_id - 1;
////上一张图片的数据
//$prev_info = $db->getOne('capture',"id=$prev_id",'*');

$tmp_result = $db->query("select id,img_path from capture where id < $curr_id order by id desc limit 1");
$prev_info = $tmp_result->fetch_assoc();
if ($prev_info != 1) {
    require_once './compare.php';
    $aHash = ImageHash::hashImageFile('./'.$prev_info['img_path']);
    $bHash = ImageHash::hashImageFile('./'.$fullName);
    if (ImageHash::isHashSimilar($aHash, $bHash) === true) {
        //与上一张图片相同，删除上一张图片的数据和图片资源
        $res = $db->deleteOne('capture',"id='$prev_info[id]'");
        if ($res) {
            unlink($prev_info['img_path']);
        }
        unlink($prev_info['img_path']);
    } else {
        dealData($fullName,$db);
    }
} else {
    dealData($fullName,$db);
}
function dealData($fullName,$db)
{
    require_once 'ocr.php';
    $ocr_arr = ocr('./'.$fullName);  //调用ocr函数，返回ocr接口的数组
//    require_once 'psc.php';
    //引入common文件，过滤和匹配数据
    require_once 'common.php';
    $business = recordInfo($ocr_arr,18);
    //截图中可能出现用户名或内容缺失的情况，暂时手动补充
    $user_length = count($business['user']);
    $info_length = count($business['info']);
    if ($user_length < $info_length) {
        array_splice($business['info'],0,1);
    }

    if ($info_length < $user_length) {
        array_splice($business['user'],-1,1);
    }

    for ($i = 0; $i<$user_length; $i++) {
        $user = $business['user'][$i];
        $info = $business['info'][$i];

        //去除同一页面内相同的商机信息
        if ($i < $user_length-1) {
            if ($user == $business['user'][$i+1] && $info == $business['info'][$i+1]) {
                continue;
            }
        }

        if ($user != '' && $info != '') {
            $res = $db->insertOne('business','user,info,img_path',"'$user','$info','$fullName'");
            if (!$res) {
                exit('插入失败');
            }
        } else {
            continue;
        }
    }
}

//关闭连接
$db->close();

//返回json格式的数据
//echo json_encode(['code' => $code, 'info' => $fullName]);
?>